<template>
  <up-modal
    :show="showModal"
    title="温馨提示"
    :content="content"
    showCancelButton
    width="500rpx"
    confirmColor="#fab6bd"
    @confirm="operateOrder"
    @cancel="showModal = false"></up-modal>
  <view class="tabs">
    <up-tabs
      :scrollable="false"
      :list="statusList"
      @click="selectStatus"
      :activeStyle="{
        color: '#bb7755',
        fontWeight: 'bold',
        transform: 'scale(1.1)',
      }"
      lineColor="#bb7755"
      lineWidth="40"></up-tabs>
  </view>

  <view class="list" v-if="detail.length > 0">
    <view class="item" v-for="item in detail" :key="item.id">
      <view class="top">
        <view class="create-time">创建时间: {{ item.createTime }}</view>
        <view class="status">{{ item.status }}</view>
      </view>
      <view class="info" @click="goOrderDetail(item)">
        <view class="detail">
          <view class="dessert">
            <up-image
              :src="`http://localhost:8080/api/files/${item.dessert.dessertImg}`"
              width="120rpx"
              height="120rpx"></up-image>
            <text class="name">{{ item.dessert.dessertName }}</text>
          </view>
        </view>
        <view class="count">
          <view class="price">{{ '￥' + item.amount }}</view>
          <view class="num">共 1 件</view>
        </view>
      </view>
      <view class="operate" v-if="item.status === '待完成'">
        <view class="cancel" @click="showConfim(item, false)">取消订单</view>
        <view class="btn">
          <up-button
            @click="showConfim(item, true)"
            type="warning"
            shape="circle"
            text="确认完成"
            :plain="true"></up-button>
        </view>
      </view>
    </view>
  </view>
  <up-empty mode="history" v-else></up-empty>
</template>

<script setup>
import { ref } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { useUserStore } from '../../stores/user.js'
import { getDessertByIdService } from '../../api/dessert.js'
import { updateBalance } from '../../api/user.js'
import { getOrderByUser, getOrderDetailService, confirmOrderService } from '../../api/order.js'

const userStore = useUserStore()
const userId = userStore.userInfo.userId

// 发送请求获取订单列表
const detail = ref([])
const details = ref({})
const orderList = ref([])
const desserts = ref([])
const getOrder = async () => {
  detail.value = []
  const res = await getOrderByUser(userId, 'diy')
  orderList.value = res.data ? res.data : []

  // 设置订单状态
  if (orderList.value.length > 0) {
    orderList.value.map(async (item) => {
      if (item.status == 4) {
        item.status = '待完成'
      } else if (item.status == 5) {
        item.status = '已完成'
      } else {
        item.status = '已取消'
      }
    })

    // 获取订单的详情数据
    orderList.value.forEach(async (item) => {
      // 获取订单详情
      const result = await getOrderDetailService(item.id)
      details.value = result.data || []
      
      // 甜品详情
      const dessert = await getDessertByIdService(details.value[0].dessertId)
      item.dessert = dessert.data || {}
      
      detail.value.push(item)
    })
  } else {
    return false
  }
}
onShow(() => {
  getOrder()
})

const statusList = ref([
  { name: '全部' },
  { name: '待完成' },
  { name: '已完成' },
  { name: '已取消' },
])
// 点击切换
const selectStatus = (sel) => {
  if (sel.name === '全部') {
    detail.value = orderList.value
  } else {
    detail.value = orderList.value.filter((item) => item.status === sel.name)
  }
}

// 确认收货
const showModal = ref(false)
const content = ref('')
const confirm = ref({})
const flags = ref(false)
const showConfim = (item, flag) => {
  showModal.value = true
  confirm.value.id = item.id
  confirm.value.userId = item.userId
  confirm.value.username = item.username
  confirm.value.phone = item.phone
  confirm.value.address = item.address
  confirm.value.message = item.message
  confirm.value.time = item.time
  confirm.value.delivery = item.delivery
  confirm.value.amount = item.amount
  confirm.value.createTime = item.createTime
  confirm.value.type = item.type
  if (flag) {
    // 确认收货
    flags.value = flag
    content.value = '您确认已完成吗？'
    confirm.value.status = 5
  } else {
    // 取消订单
    flags.value = flag
    content.value = '您确认取消订单吗？'
    confirm.value.status = 6
  }
}

const operateOrder = async () => {
  // 发送请求 确认收货或确认取消订单
  const res = await confirmOrderService(confirm.value)
  if (res.code === '0') {
    // 取消订单
    if(confirm.value.status == 6) {
      const reduce = parseFloat(userStore.userInfo.balance + confirm.value.amount).toFixed(2)
      // 更新用户余额
      const balance = await updateBalance(userStore.userInfo.userId, reduce)
      if(balance.code == 0) {
        userStore.updateBalance(reduce)
      }
    }
    uni.showToast({
      title: flags.value ? '已确认完成' : '已取消订单',
      icon: 'none',
    })
    getOrder()
  } else {
    uni.showToast({
      title: flags.value
        ? '确认完成失败，请联系店家'
        : '取消订单失败，请联系店家',
      icon: 'none',
    })
  }
  showModal.value = false
}

// 跳转到订单详情页
const goOrderDetail = (item) => {
  uni.navigateTo({
    url: `/pages/orderDetail/orderDetail?diyOrder=${encodeURIComponent(
      JSON.stringify(item)
    )}`,
  })
}
</script>

<style lang="scss" scoped>
.tabs {
  width: 102%;
  background-color: #fff;
  border-radius: 10rpx;
  text-align: center;
  box-sizing: border-box;
  margin-left: -10rpx;
  margin-bottom: 20rpx;
}

.list {
  width: 100%;
  text-align: center;
  .item {
    width: 95%;
    height: auto;
    background-color: #fff;
    border-radius: 10rpx;
    margin: 0 auto;
    padding: 10rpx 20rpx;
    box-sizing: border-box;
    margin-bottom: 10rpx;
    .top {
      display: flex;
      align-items: center;

      .create-time {
        font-size: 30rpx;
        color: #666;
        margin-top: 10rpx;
      }

      .tag {
        margin-top: -10rpx;
      }

      .status {
        margin-left: auto;
      }
    }
    .info {
      width: 100%;
      display: flex;
      align-items: center;
      overflow: hidden;
      .detail {
        width: 500rpx;
        margin-top: 20rpx;
        display: flex;
        flex-wrap: nowrap;
        align-items: center;
        overflow-x: auto;

        .dessert {
          flex: 0 0 auto;
          width: 120rpx;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          display: inline-block;
          text-align: center;
          margin-right: 10rpx;

          .name {
            font-size: 28rpx;
            color: #888;
          }
        }
      }

      .count {
        margin-top: 10rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: space-between;
        margin-left: auto;

        .price {
          font-weight: bold;
          font-size: 30rpx;
          color: #bb7755;
        }

        .num {
          font-size: 28rpx;
          color: #666;
        }
      }
    }

    .operate {
      width: 50%;
      display: flex;
      align-items: center;
      margin-left: auto;
      margin-right: -10rpx;

      .cancel {
        width: 50%;
        font-size: 28rpx;
        color: #666;
        transition: all linear 0.3s;
      }

      .btn {
        width: 50%;
      }
    }
  }
}
</style>
